package com.qinyu.treehole.config;

import com.qinyu.treehole.interceptor.UserAuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig implements WebMvcConfigurer {

    /**
     * 解决跨域问题
     * @return
     */
    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*");

            }
        };
    }

    /**
     * 通用，以json格式序列化
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisTemplate<Object, Object> jsonRedisTemplate(RedisConnectionFactory connectionFactory) {
        final RedisTemplate<Object, Object> template =  new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 设置key 的序列化
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setKeySerializer(jsonRedisSerializer);
        template.setHashKeySerializer(jsonRedisSerializer);
        // 设置value 的序列化
        template.setHashValueSerializer(jsonRedisSerializer);
        template.setValueSerializer(jsonRedisSerializer);

        return template;
    }

    @Bean
    public UserAuthInterceptor userAuthInterceptor(){
        return new UserAuthInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userAuthInterceptor()).addPathPatterns("/api/**");
    }
}
